import os
import sys
import re
if hasattr(sys, 'frozen'):
    os.environ['PATH'] = sys._MEIPASS + ";" + os.environ['PATH']
from PyQt5.QtWidgets import QWidget,QApplication,QFileDialog,QMessageBox
from mainWin import *
import time
from Message import Message
from Signal import Signal
from CreatCode import CreatCode
class Main(QWidget,Ui_MainWin):
    def __init__(self):
        super(Main, self).__init__()

        self.setupUi(self)
        self.lineEdit.setText(os.path.abspath(os.path.dirname(os.getcwd())) + '\配置.txt')
        self.pushButton_openfile.clicked.connect(self.OpenDBC)
        self.pushButton_startcreat.clicked.connect(self.StartCreat)
        self.pushButton_filesave.clicked.connect(self.choiceDir)
        self.busChl = 'Evbus'
        self.checkBox_Evbus.stateChanged.connect(self.checkBox_Evbus_checked)
        self.checkBox_Pbus.stateChanged.connect(self.checkBox_Pbus_checked)
        self.comboBox_choseNode.currentIndexChanged[str].connect(self.Get_NodeName)
        #self.timeCurrent = time.strftime('%Y-%m-%d',time.localtime(time.time()))
        self.lineEdit_codesave_path.setText(os.path.abspath(os.path.dirname(os.getcwd())))
        self.saveDir = self.lineEdit_codesave_path.text()
        self.show()
    #复选框选中处理函数
    def checkBox_Evbus_checked(self):
        if self.checkBox_Evbus.isChecked() == True:
            self.busChl = 'Evbus'
            self.checkBox_Pbus.setChecked(False)
    def checkBox_Pbus_checked(self):
        if self.checkBox_Pbus.isChecked() == True:
            self.busChl = 'Pbus'
            self.checkBox_Evbus.setChecked(False)
    #打开需要读取的DBC文件
    def OpenDBC(self):
        self.fname = QFileDialog.getOpenFileName(self,'打开文件','./',('DBC文件(*.dbc)'))
        if self.fname[0]:
            self.lineEdit.setText(self.fname[0])  #记录文件位置
            if 'DBC文件(*.dbc)'== self.fname[1]:
                self.Creater = CreatCode(self.busChl,self.lineEdit_authorName.text(),self.lineEdit.text())
                #self.Creater.Get_signalInfo(self.lineEdit.text()) #获取dbc文件内容
                self.comboBox_choseNode.clear()
                self.comboBox_choseNode.addItems(self.Creater.nodeName_array)
    #获取下拉框内当前选择节点的名称
    def Get_NodeName(self,nodeName):
        self.nodeName = nodeName
        for msg_info in self.Creater.msg_array:
            if nodeName == msg_info.msg_node:
                msg_info.msg_dirc = 'Tx'
            else:
                msg_info.msg_dirc = 'Rx'
        self.Creater.MsgRx_List.clear()
        self.Creater.MsgTx_List.clear()
        self.Creater.MsgRx_List = [msg for msg in self.Creater.msg_array if msg.msg_dirc == 'Rx']
        self.Creater.MsgTx_List = [msg for msg in self.Creater.msg_array if msg.msg_dirc == 'Tx']
        self.Creater.MsgRx_List.sort(key=Message.Get_msgId)
        self.Creater.MsgTx_List.sort(key=Message.Get_msgId)
        self.Creater.msg_array = self.Creater.MsgRx_List + self.Creater.MsgTx_List
    #选择生成代码存放目录
    def choiceDir(self):
        Dir_path = QFileDialog.getExistingDirectory(self,'请选择保存源代码路径','./')
        if Dir_path:
            self.lineEdit_codesave_path.setText(Dir_path)
        self.saveDir = self.lineEdit_codesave_path.text()
    #开始生成代码
    def StartCreat(self):
        #尝试打开选定路径文件,若是文件不存在则弹窗警告
        try:
            f_read = open(self.lineEdit.text(),'r',encoding='utf-8')
        except FileNotFoundError:
            QMessageBox.warning(self,'提示','并未找到所选路径配置文件,请检查路径')
            return
        try:
            self.Creater.saveDirpath = self.saveDir
            self.Creater.CreatCode_MainFun()
            #os.system('start explorer ' + self.lineEdit_codesave_path.text().replace('/','\\'))
            QMessageBox.information(self,'提示','代码生成完毕')
            os.system('start explorer ' + self.lineEdit_codesave_path.text().replace('/','\\'))
        except Exception as e:
            QMessageBox.warning(self,'提示','代码生成失败:' + e.args[0])


if __name__ == '__main__':
    try:
        app = QApplication(sys.argv)
        MainFun = Main()
        sys.exit(app.exec_())
    except Exception as ex:
        print(ex.args)